<script setup>
import { getAllUserAPI, loginApi } from "@/apis/login";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const username = ref("");
const password = ref("");

if (process.env.NODE_ENV === "development") {
  username.value = "admin";
  password.value = "123456";
}

const handleLogin = async () => {
  try {
    const res = await loginApi({
      username: username.value,
      password: password.value,
    });
    if (res.code) {
      localStorage.setItem("token", res.data.token);
      router.push("/mainbox");
    } else {
      localStorage.removeItem("token");
    }
  } catch (error) {
    console.error(error.message);
  }
};

const userList = ref([]);
onMounted(async () => {
  const res = await getAllUserAPI();
  userList.value = res.data.map((i) => i);
  console.log(userList.value);
});
</script>

<template>
  <form class="login">
    <div><span>用户名：</span><input type="text" v-model="username" /></div>
    <div><span>密码</span><input type="password" v-model="password" /></div>
  </form>
  <button @click="handleLogin">登陆</button>

  <table border>
    <tbody>
      <tr>
        <th>用户名</th>
        <th>密码</th>
        <th>头像</th>
      </tr>
      <tr v-for="item in userList" :key="item._id">
        <td>{{ item.username }}</td>
        <td>{{ item.password }}</td>
        <td><img :src="`/api${item.avata}`" alt="" /></td>
      </tr>
    </tbody>
  </table>
</template>

<style lang="scss" scoped>
//
.login {
  width: 300px;
  display: flex;
  flex-direction: column;
}
img {
  height: 50px;
  width: 50px;
  object-fit: fill;
}
</style>
